const mongoose = require('mongoose');

const unitSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, '单位名称为必填项'],
    unique: true,
    trim: true
  },
  shortName: {
    type: String,
    trim: true
  },
  calibrationCode: {
    type: String,
    unique: true,
    sparse: true,
    trim: true
  },
  receiptCode: {
    type: String,
    trim: true
  },
  unitType: {
    type: String,
    required: [true, '单位类型为必填项'],
    enum: ['国家机关', '事业单位', '国有企业', '社会团体', '其他']
  },
  unitLevel: {
    type: String,
    enum: ['正部级', '副部级', '正局级', '副局级', '正处级', '其他']
  },
  contactPerson: {
    type: String,
    trim: true
  },
  landlinePhone: {
    type: String,
    required: [true, '座机号码为必填项'],
    trim: true,
    validate: {
      validator: function(v) {
        return /^(\d{3,4}-?)?\d{7,8}$/.test(v);
      },
      message: '请输入有效的座机号码'
    }
  },
  mobilePhone: {
    type: String,
    required: [true, '手机号码为必填项'],
    trim: true,
    validate: {
      validator: function(v) {
        return /^1[3-9]\d{9}$/.test(v);
      },
      message: '请输入有效的手机号码'
    }
  },
  remarks: {
    type: String,
    trim: true
  }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// 虚拟字段：关联的干部数量
unitSchema.virtual('cadreCount', {
  ref: 'Cadre',
  localField: '_id',
  foreignField: 'unitId',
  count: true
});

// 索引 (name字段已通过unique:true自动创建索引)
unitSchema.index({ unitType: 1 });
unitSchema.index({ unitLevel: 1 });

module.exports = mongoose.model('Unit', unitSchema);
